import axios from "../../axios";
import store from "../store";
import { setOnlineMsgAction } from "../actionCreator/chat";
function chatReducer(state = {
  // 消息列表
  msgList: [],
  // 收到的离线消息
  offlineMsgList: [],
  // 收到的在线消息
  onlineMsg: {
    _id: ''
  },
  tabBarBadge: 0
}, action) {

  let preState = deepClone(state)
  console.log('pk******************************************')
  switch (action.type) {
    case 'setMsgList':
      console.log('出发了', action)
      preState.msgList = action.data
      preState.tabBarBadge = setNewMsgNum([...preState.msgList])
      return preState;
    case 'setOfflineMsg':
      console.log(action)
      preState.offlineMsgList = action.data
      setOfflineMsg(action.data)
      return preState;
    case 'setOnlineMsg':
      console.log(action)
      preState.onlineMsg = action.data
      editNewMsg(preState, action.data)
      preState.tabBarBadge = setNewMsgNum(preState.msgList)
      return preState;
    case 'sendMsgSuccess':
      console.log('sendMsgSuccess')
      sendMsgSuccess(preState, action.data)
      return preState
    case 'addNewFriend':
      console.log('addNewFriend')
      addNewFriend(preState, action.data)
      return preState
    case 'setTabBarBadge':
      preState.tabBarBadge = action.data
      return preState
    case 'resetUnreadMsg':
      console.log('resetUnreadMsg', action)
      resetUnreadMsg(preState, action.data)
      preState.tabBarBadge = setNewMsgNum(preState.msgList)
      return preState
    default:
      return preState;
  }
}
// 标记消息已读
const resetUnreadMsg = (state, userId) => {
  // 客户端数据处理
  state.msgList.some((item, i) => {
    if (userId === item.friend._id) {
      state.msgList[i].unreadMsgNum = 0
    }
    return userId === item.friend._id
  })
  // 后台数据处理,把当前用户的消息全部标记为已读状态
  axios.put('/chat', {
    fromUser: userId
  }).then(() => {
    console.log('消息已标记为已读')
  })
  // return state
}

const setNewMsgNum = (list) => {
  let num = 0
  list.forEach(item => {
    num += item.unreadMsgNum
  })
  return num
}
// 新增好友，把好友加入列表
const addNewFriend = (state, data) => {
  if (!state.msgList.some(item => item.friend._id === data.friend._id)) {
    state.msgList.unshift(data)
  }
  // return state
}
const setOfflineMsg = (state, list) => {
  console.log('setOfflineMsg', list)
  list.forEach(item => {
    store.dispatch(setOnlineMsgAction(item))
  })
  return state
}
const sendMsgSuccess = (state, data) => {
  state.msgList = state.msgList.map(item => {
    if (item.friend._id === data.toUser._id) {
      return {
        ...item,
        content: data.content,
        createTime: data.createTime
      }
    }
    return item
  })
  return state
}

// 收到新消息设置对应消息的角标数量
const editNewMsg = (state, newMsg) => {
  console.log('深拷贝', state)
  console.log('editNewMsg', newMsg)
  let newMsgUserId
  if (newMsg.fromUser._id) {
    newMsgUserId = newMsg.fromUser._id
  } else {
    newMsgUserId = newMsg.fromUser
  }
  // 处理已经在消息列表的用户消息逻辑
  if (state.msgList.some(item => item.friend._id === newMsgUserId)) {
    // 新消息插入最前面
    const index = state.msgList.findIndex((item) => item.friend._id === newMsgUserId)
    // copy
    const current = {
      ...state.msgList[index]
    }
    // 删除
    state.msgList.splice(index, 1)
    // 再插入copy的消息在最前面
    state.msgList.unshift({
      ...current,
      content: newMsg.content,
      // 判断收到的新消息是否是已读状态，比如是正在对方的聊天窗口页面，则收到就是已读消息
      unreadMsgNum: newMsg.isRead ? current.unreadMsgNum : current.unreadMsgNum + 1
    })
  } else {
    // 处理还没有聊过天的用户逻辑
    state.msgList.unshift({
      ...newMsg,
      friend: newMsg.fromUser,
      unreadMsgNum: 1
    })
  }
  console.log('state==>', state)
  return state
}

function deepClone(data) {
  // 判断数据类型为 Array or Object
  let cloneObject = Array.isArray(data) ? [] : {}
  // 遍历数组或对象
  for (let indexOrKey in data) {
    // console.log('arguments.callee', arguments.callee)
    // 引用数据类型，且有值(null为object类型)
    if (data[indexOrKey] && typeof data[indexOrKey] === 'object') {
      // 把当前索引的对象继续递归，直到没有引用数据类型为止
      cloneObject[indexOrKey] = deepClone(data[indexOrKey])  // arguments.callee递归解耦，方法名deepClone改变不影响递归函数
    } else {
      // 基本数据类型,直接赋值
      cloneObject[indexOrKey] = data[indexOrKey]
    }
  }
  // 返回拷贝对象
  return cloneObject;
}

export default chatReducer